#!/bin/bash
# =================================================================
# This is the dcm2xnat wrapper designed to work with storescp.
# It effectively will run dcm2xnat in the background and exit 0.
# =================================================================

#if [ "$(id -u)" != "0" ]; then
#   echo "This script must be run as root" 1>&2
#   exit 1
#fi

dir=$1
prog=`basename $0`;

if test -z "$dir" -o -n "$2"; then
    echo "Usage: $prog dicom_dir";
    exit 1;
fi

echo "Running: '$prog' on '$dir'"

export INCOMING_DIR=/mnt/CBSCentral/Incoming
export OUTGOING_DIR=/mnt/CBSCentral/PreArchive
export LOG_DIR=/XNAT/Logs
export XNAT_INSTALL=CBS
export AE_TITLE=CBS
export DCM2XNAT_PROG=/home/vmuser/perl-xnat/dcm2xnat

export DCMDICTPATH=/usr/share/dcmtk/dicom.dic
export DCMDATAPATH=$INCOMING_DIR

export DIR_PREFIX=${AE_TITLE}
export DCM2XNAT_FLAGS=" --verbose --extra --dir-prefix ${DIR_PREFIX} --in-dir ${INCOMING_DIR} --prearchive ${OUTGOING_DIR}"
export LOG_STAMP=`date +'%Y.%m.%d-%H.%M'`;
export LOG_FILE="${LOG_DIR}/${LOG_STAMP}-$prog-$$.log"

if [ ! -e "${INCOMING_DIR}" ]; then
    echo "ERROR: No such directory '${INCOMING_DIR}'!";
    exit -1;
fi

if [ ! -e "${OUTGOING_DIR}" ]; then
    echo "ERROR: No such directory '${OUTGOING_DIR}'!";
    exit -1;
fi

if [ ! -e "${LOG_DIR}" ]; then
    echo -n "Creating '${LOG_DIR}':";
    if mkdir -p "${LOG_DIR}"; then
	echo " OK"
    else
	echo " ERROR!"
	exit -1;
    fi
fi

echo nohup nice -n 10 ${DCM2XNAT_PROG} ${DCM2XNAT_FLAGS} $dir
echo nohup nice -n 10 ${DCM2XNAT_PROG} ${DCM2XNAT_FLAGS} $dir >> "${LOG_FILE}"
nohup nice -n 10 ${DCM2XNAT_PROG} ${DCM2XNAT_FLAGS} $dir 2>> "${LOG_FILE}" >> "${LOG_FILE}" &
exit 0;
